package top.cyuw.simplerpc.config;

import lombok.extern.slf4j.Slf4j;
import top.cyuw.simplerpc.exception.RpcException;
import top.cyuw.simplerpc.extension.ExtensionLoader;
import top.cyuw.simplerpc.registry.ServiceRegistry;
import top.cyuw.simplerpc.registry.ServiceRegistrySelector;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author chen
 * @date 2023/3/12 20:31
 */
@Slf4j
public class RpcShutdownHook extends Thread {

    private final AtomicBoolean registered = new AtomicBoolean(false);

    private final AtomicBoolean destroyed = new AtomicBoolean(false);

    @Override
    public void run() {
        if (destroyed.compareAndSet(false, true)) {
            log.info("simple-rpc shutdown now.");
            doDestroy();
        }
    }

    private void doDestroy() {
        String serviceRegistryName = ServiceRegistrySelector.getServiceRegistry();
        ServiceRegistry serviceRegistry = ExtensionLoader.of(ServiceRegistry.class).getExtension(serviceRegistryName);
        serviceRegistry.clear();
    }

    public void register() {
        setName("simplerpc-shutdown-hook");
        if (registered.compareAndSet(false, true)) {
            try {
                Runtime.getRuntime().addShutdownHook(this);
            } catch (Exception e) {
                throw new RpcException("register shutdown hook failed: " + e.getMessage(), e);
            }
        }
    }

    public boolean isRegistered() {
        return registered.get();
    }
}
